﻿using System;
using System.Data.SqlClient;
using System.IO;

namespace Utilities
{
    public class ConfigHelper
    {
        public static string Server { get; set; }
        public static String Database { get; set; }
        public static String Username { get; set; }
        public static String Password { get; set; }
        private const string PATH_CONFIG = "config.txt";

        public static void Initiaties()
        {
            try
            {
                var reader = new StreamReader(PATH_CONFIG);
                Server = reader.ReadLine().Split('=')[1];
                Database = reader.ReadLine().Split('=')[1];
                Username = reader.ReadLine().Split('=')[1];Password = reader.ReadLine().Split('=')[1];
            }
            catch
            {
            }
        }

        public static SqlConnection GetConnection()
        {
            string strConnection;
            if(Username!="")
             strConnection = String.Format("server={0};Database={1};User Id={2};Password={3};", Server, Database, Username, Password);
            else
            {
                strConnection = String.Format("server={0};Database={1};Integrated security=true;",Server,Database);
            }
            return new SqlConnection(strConnection);
        }

        public static void WriteConfigToFile()
        {
            try
            {
                var writer = new StreamWriter(PATH_CONFIG);
                writer.WriteLine("server =" + Server);
                writer.WriteLine("Database =" + Database);
                writer.WriteLine("Username =" + Username);
                writer.WriteLine("Password =" + Password);
                writer.Close();
            }
            catch
            {
            }
        }

        public static void WriteConfigToFile(string server, string database, string username, string password)
        {
            Server = server;
            Database = database;
            Username = username;
            Password = password;
            WriteConfigToFile();
        }

        public static bool TestConnection(String strConnection)
        {
            try
            {
                var con = new SqlConnection(strConnection);
                con.Open();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

    }
}
